package com.dongdongshop.shiro;

import com.dongdongshop.api.SellerApi;
import com.dongdongshop.api.SystemApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.AdminDTO;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.enums.LoginTypeEnum;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.exception.BaseException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SystemApi systemApi;

    @Autowired
    private SellerApi sellerApi;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        DdUsernamePasswordToken ddToken=(DdUsernamePasswordToken)authenticationToken;

        if (ddToken.getLoginEnum().equals(LoginTypeEnum.ADMIN)){
            String username = ddToken.getUsername();
            Result<AdminDTO> adminUser = systemApi.getAdminUser(username);
            AdminDTO userData = adminUser.getData();
            if (userData.getId() == null){
                throw new BaseException(ResultEnum.USERNAME_PASSWORD_ERROR.getMessage());
            }
            return new SimpleAuthenticationInfo(userData,userData.getPassword(), ByteSource.Util.bytes(userData.getSalt()),"adminUser");
        } else if (ddToken.getLoginEnum().equals(LoginTypeEnum.SELLER)) {
                String username = ddToken.getUsername();
                Result<SellerDTO> adminUser =sellerApi.getSellerInfo(username);
                SellerDTO userData = adminUser.getData();
                if (userData.getSellerId() == null){
                    throw new BaseException(ResultEnum.USERNAME_PASSWORD_ERROR.getMessage());
                }
                if (!userData.getStatus().equals("1")){
                    throw new BaseException(ResultEnum.SELLER_LOGIN_STATUS_ERROR.getMessage());
                }
                return new SimpleAuthenticationInfo(userData,userData.getPassword(), ByteSource.Util.bytes(userData.getSalt()),"sellerUser");
        }
        return null;
    }
}
